//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    code: '',
    isLogin: false,
    motto: 'Hello World',
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    let phone = wx.getStorageSync('phone');
    if (phone) {
      this.setData({
        isLogin: true
      })
    }
    // 登录
    wx.login({
      success: res => {
        // 一个code只能登录一次，每一次调用wx.login都会获得一个code
        this.setData({
          code: res.code
        })
      }
    });  
  },

  // 获取用户信息，然后登陆
  getUserInfo: function (e) {
    let { iv, encryptedData, userInfo } = e.detail;
    app.globalData.userInfo = userInfo
    this.setData({
      userInfo,
      hasUserInfo: true
    })

    // 登录
    let url = '/user/login';
    let code = this.data.code;
    let data = {
      phone: 13800000000,
      code, iv, encryptedData, userInfo
    } 
    app.post(url,data).then(res=> {
      console.log(res);
      wx.setStorageSync('token', res.user.token);
      this.setData({
        isLogin: true
      })
    }).catch(err=> {
      console.log(err);
    })
  }
})
